package com.zhongfeng.api.modules.img.controller;

import com.zhongfeng.api.modules.img.service.Imgservice;
import com.zhongfeng.api.modules.utils.file.ImgUtil;
import com.zhongfeng.api.modules.utils.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;


/**
 * <p>描述:   图片和视频上传和查看。</p>
 * <p>文件名称: Controller.java</p>
 * <p>创建时间: 2022-07-08 </p>
 *
 * @author 万笑佛
 * @since 2022-07-08
 */

@RestController
@Slf4j
@RequestMapping("/api/image")
public class ImgController {

    @Autowired
    Imgservice imgservice;

    /**
     * 图片上传
     *
     * @param
     * @return JSONObject
     */
    @PostMapping(value = "/upload")
    public Result imageUpload(@RequestParam MultipartFile file, HttpServletRequest request) {
        return imgservice.saveImg(file, request);
    }

    /**
     * 查看图片
     *
     * @param request
     * @param response
     * @param session
     * @return
     * @throws Exception
     */
    @GetMapping("/showphoto")
    public void showPhoto(@RequestParam String photoName,HttpServletRequest request, HttpServletResponse response, HttpSession session)
            throws Exception {
        System.out.println(photoName);
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        // 获得的系统的根目录
        File fileParent = new File(File.separator);
        System.out.println(fileParent);
        File file = new File("img/"+photoName);
        if (file.exists()){
            Image img=Toolkit.getDefaultToolkit().getImage("img/"+photoName);
            BufferedImage bufferedImage = ImgUtil.toBufferedImage(img);
            ServletOutputStream servletOutputStream = response.getOutputStream();
            ImageIO.write(bufferedImage, "jpg", servletOutputStream);
            try {
                servletOutputStream.flush();
            } finally {
                servletOutputStream.close();
            }
        }
    }
}